package collection.map;

import java.util.Map;
import java.util.TreeMap;

public class TreeMapDemo {
    public static void main(String[] args) {
        // 1. 自然排序（按键的自然顺序）
        Map<String, Integer> treeMap = new TreeMap<>();
        treeMap.put("banana", 3);
        treeMap.put("apple", 5);
        treeMap.put("cherry", 2);
        System.out.println("按自然顺序排序：" + treeMap);

        // 2. 自定义排序
        // 按年龄降序排序
        Map<Student, String> studentMap = new TreeMap<>((s1, s2) ->
                Integer.compare(s2.getAge(), s1.getAge()));

        studentMap.put(new Student("张三", 20), "一班");
        studentMap.put(new Student("李四", 18), "二班");
        studentMap.put(new Student("王五", 22), "三班");

        System.out.println("\n按年龄降序排序：");
        for (Map.Entry<Student, String> entry : studentMap.entrySet()) {
            System.out.println(entry.getKey() + "：" + entry.getValue());
        }
    }

    static class Student {
        private String name;
        private int age;

        public Student(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public int getAge() { return age; }

        @Override
        public String toString() {
            return name + "(" + age + ")";
        }
    }
}
